<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use App\Models\User;

class ApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        try {
//            if (!$user = JWTAuth::parseToken()->authenticate()) {
//                //获取到用户数据，并赋值给$user
//                return response()->json([
//                    'status' => 0,
//                    'msg' => '系统无此用户'
//                ]);
//            }
//
//            $request->merge(['uid' => $user->uid]);
//            return $next($request);
//        } catch (TokenExpiredException $e) {
//            return response()->json([
//                'status' => 0,
//                'msg' => 'token 过期', //token已过期
//            ]);
//        } catch (TokenInvalidException $e) {
//            return response()->json([
//                'status' => 0,
//                'msg' => 'token 无效',  //token无效
//            ]);
//        } catch (JWTException $e) {
//            return response()->json([
//                'status' => 0,
//                'msg' => '缺少token', //token为空
//            ]);
//        }
        $token = $request->token;
        if (!$token) {
            return response()->json([
                'status' => '-60',
                'msg' => '缺少签名信息',
                'data' => '',
            ]);
        }

        $newToken = null;
        $auth = JWTAuth::parseToken();

        if (!$token = $auth->setRequest($request)->getToken()) {
            return response()->json([
                'status' => '-50',
                'msg' => '无参数token',
                'data' => '',
            ]);
        }

        try {
            $user = $auth->authenticate($token);
            if (!$user) {
                return response()->json([
                    'status' => '-30',
                    'msg' => '未查询到该用户信息',
                    'data' => '',
                ]);
            }
            $request->merge(['uid' => $user->uid]);
            $request->headers->set('Authorization', 'Bearer ' . $token);
        } catch (TokenExpiredException $e) {
            try {
                sleep(rand(1, 5) / 100);
                $newToken = JWTAuth::refresh($token);
                $request->headers->set('Authorization', 'Bearer ' . $newToken); // 给当前的请求设置性的token,以备在本次请求中需要调用用户信息
                // 将旧token存储在redis中,30秒内再次请求是有效的
//                Redis::setex('token_blacklist:'.$token,30,$newToken);
            } catch (JWTException $e) {
                // 在黑名单的有效期,放行
//                if($newToken = Redis::get('token_blacklist:'.$token)){
//                    $request->headers->set('Authorization','Bearer '.$newToken); // 给当前的请求设置性的token,以备在本次请求中需要调用用户信息
//                    return $next($request);
//                }
                // 过期用户
                return response()->json([
                    'status' => '-20',
                    'msg' => '账号信息过期了，请重新登录',
                ]);
            }
        } catch (JWTException $e) {
            return response()->json([
                'status' => '-40',
                'msg' => '无效token',
                'data' => '',
            ]);
        }
        $response = $next($request);

        if ($newToken) {
            $user = $auth->authenticate($token);
            $request->merge(['uid' => $user->uid]);
            $response->headers->set('Authorization', 'Bearer ' . $newToken);
        }

        return $response;
    }
}
